package com.ljt.springsecuritylogin;

import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;


@RequiredArgsConstructor
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final JwtService jwtService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String header = request.getHeader("Authorization");
        if (header == null || !header.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }
        header = header.replace("Bearer ", "");
        if (!jwtService.validateToken(header)){
            filterChain.doFilter(request, response);
            return;
        };

        // 令牌校验通过，认证成功。
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                jwtService.getUsername(header),
                null,
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_"+jwtService.getRole(header).name()))
        );

        // 把request的ip信息都直接
        authentication.setDetails(
                new WebAuthenticationDetailsSource().buildDetails(request)
        );

        // 保存登录态
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 交给下一个拦截器处理
        filterChain.doFilter(request, response);
    }
}
